<?php
/**
 * Created by PhpStorm.
 * User: server
 * Date: 2019/5/23
 * Time: 10:09
 */

namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path'), EXT);

use app\admin\Controller;
use think\Db;
use think\Config;
use think\Request;

class DriverInvoice extends Controller
{

    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        $data = input();
//        halt($data);
        $map = [];

        if (!empty($data['dispatch_group_id'])) {
            $map['di.dispatch_group_id'] = ['=', $data['dispatch_group_id']];
        }

        if (!empty($data['title'])) {
            $map['r.title'] = ['like', "%{$data['title']}%"];
        }

        if (!empty($data['realname'])) {
            $map['au.realname'] = ['like', "%{$data['realname']}%"];
        }

        if (!empty($data['plate_number'])) {
            $map['d.plate_number'] = ['like', "%{$data['plate_number']}%"];
        }

        if (!empty($data['invoice_type'])) {
            $map['di.invoice_type'] = ['like', "%{$data['invoice_type']}%"];
        }

        if (!empty($data['invoice_code'])) {
            $map['di.invoice_code'] = ['like', "%{$data['invoice_code']}%"];
        }

        if (!empty($data['invoice_num'])) {
            $map['di.invoice_num'] = ['like', "%{$data['invoice_num']}%"];
        }

        if ($this::$isdelete) {
            $map['di.isdelete'] = 1;
        } else {
            $map['di.isdelete'] = 0;
        }

        $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");

        $list = Db::name('driver_invoice')
            ->alias('di')
            ->join('tp_dispatch_traveler_group dtg', 'di.dispatch_group_id=dtg.id', 'left')
            ->join('tp_admin_user au', 'dtg.driver_user_id=au.id', 'left')
            ->join('tp_route r', 'dtg.route_id=r.id', 'left')
            ->join('tp_driver d', 'dtg.driver_user_id=d.user_id', 'left')
            ->field('di.*,au.realname,r.title,d.plate_number,au.id as driver_user_id')
            ->where($map)
            ->order('di.id','desc')
            ->paginate($listRows, false, ['query' => $this->request->get()]);

        $this->view->assign('list', $list);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        return $this->view->fetch();
    }

    /**
     * 电子表格
     * @return mixed
     */
    public function get_excel(Request $request)
    {
        $data = input();
        ini_set('max_execution_time', 3600);//1小时
        ini_set('memory_limit', '500M');
        Vendor('PHPExcel.PHPExcel');
        Vendor('PHPExcel.PHPExcel.WorkSheet.Drawing');
        Vendor('PHPExcel.PHPExcel.Writer.Excel2007');
        //实例化
        $export_excel = new \PHPExcel();
        //设置文档属性
        $writer = \PHPExcel_IOFactory::createWriter($export_excel, 'Excel2007');
        //设置内容
        $export_sheet = $export_excel->getActiveSheet();
        for ($l = 0; $l < 26; $l++) {
            $letter[] = chr($l + 65);
        }
        $countChr = count($letter);
        for ($j = 0; $j < $countChr; $j++) {
            for ($k = 0; $k < $countChr; $k++) {
                $letter[] = $letter[$j] . $letter[$k];
            }
        }
        $tableHeader = ['司机', '司机类型', '路线名称', '车牌号', '派车单号', '发票类型', '发票代码', '发票号码', '发票金额', '合计', '备注'];
        $tableLength = count($tableHeader);
        for ($i = 0; $i < $tableLength; $i++) {
            $export_sheet->setCellValue("$letter[$i]1", "$tableHeader[$i]");
            $export_sheet->getColumnDimension("$letter[$i]")->setWidth(20);
        }
        $map = array();

        //选择导出数据
        if ($data['id']) {
            $id = implode($data['id'], ',');
            $map['di.id'] = ['in', $id];
        }

        if (!empty($data['dispatch_group_id'])) {
            $map['di.dispatch_group_id'] = ['=', $data['dispatch_group_id']];
        }

        if (!empty($data['title'])) {
            $map['r.title'] = ['like', "%{$data['title']}%"];
        }

        if (!empty($data['realname'])) {
            $map['au.realname'] = ['like', "%{$data['realname']}%"];
        }

        if (!empty($data['plate_number'])) {
            $map['d.plate_number'] = ['like', "%{$data['plate_number']}%"];
        }

        if (!empty($data['invoice_type'])) {
            $map['di.invoice_type'] = ['like', "%{$data['invoice_type']}%"];
        }

        if (!empty($data['invoice_code'])) {
            $map['di.invoice_code'] = ['like', "%{$data['invoice_code']}%"];
        }

        if (!empty($data['invoice_num'])) {
            $map['di.invoice_num'] = ['like', "%{$data['invoice_num']}%"];
        }

        if ($this::$isdelete) {
            $map['di.isdelete'] = 1;
        } else {
            $map['di.isdelete'] = 0;
        }

        $list = Db::name('driver_invoice')
            ->alias('di')
            ->join('tp_dispatch_traveler_group dtg', 'di.dispatch_group_id=dtg.id', 'left')
            ->join('tp_admin_user au', 'dtg.driver_user_id=au.id', 'left')
            ->join('tp_route r', 'dtg.route_id=r.id', 'left')
            ->join('tp_driver d', 'dtg.driver_user_id=d.user_id', 'left')
            ->field('au.realname,d.driver_type,r.title,d.plate_number,dtg.id,di.invoice_type,di.invoice_code,di.invoice_num,di.invoice_money,di.total,di.remark')
            ->where($map)
            ->order('di.id desc')
            ->select();

        foreach ($list as $k => $v) {


        }

        if (!empty($list)) {
            $tableKey = array_keys($list[0]);
            //填充表格信息
            $tableKeyLength = count($tableKey);
            foreach ($list as $tk => $tv) {
                $tk += 2;
                for ($i = 0; $i < $tableKeyLength; $i++) {
                    $export_sheet->setCellValue("$letter[$i]" . $tk, $tv[$tableKey[$i]]);
                }
            }
        }
        //定义table键
        if (!empty($list)) {
            $tableKey = array_keys($list[0]);
            //填充表格信息
            $tableKeyLength = count($tableKey);
            foreach ($list as $tk => $tv) {
                $tk += 2;
                for ($i = 0; $i < $tableKeyLength; $i++) {
                    $export_sheet->setCellValue("$letter[$i]" . $tk, $tv[$tableKey[$i]]);
                }
            }
        }
        $fileName = date('YmdHis', time()) . "司机发票统计-司机发票统计数据.xls";
        $fileName = iconv('utf-8', 'gb2312', $fileName);
        ob_end_clean();
        if ($request->isGet()) {
            header('Content-Type:application/force-download');
            header('Content-Type:application/octet-stream');
            header('Content-Type:application/download');
            header('Content-Disposition:inline;filename=' . $fileName);
            header('Content-Transfer-Encoding:binary');
            header('Cache-Control:must-revalidate,post-check=0');
            header('Pragma:no-cache');
            $writer->save('php://output');
            exit();
        } else {
            // 保存文件到服务器上
            $path = ROOT_PATH . "public/excel";
            // 判断文件是否存在
            if (!file_exists($path)) {
                mkdir($path, 0777, true);
            }
            $fileName = iconv('gb2312', 'utf-8', $fileName);
            $file = $path . "/{$fileName}";
            $writer->save($file);
            $url = $request->domain() . "/excel/{$fileName}";
            return ajax_return_adv($url, '', '', '', '', '', 5);
        }
    }

    /**
     * 添加
     * @return mixed
     */
    public function add()
    {
        $data = input();

        if ($this->request->isAjax()) {

            $travelers = [];
            $total = 0;

            // 数据处理
            if (is_array($data['traveler']['invoice_type'])) {
                foreach ($data['traveler']['invoice_type'] as $k => $v) {
                    $traveler['driver_user_id'] = Db::name('dispatch_traveler_group')
                        ->where('id',$data['dispatch_group_id'])
                        ->value('driver_user_id');
                    $traveler['dispatch_group_id'] = $data['dispatch_group_id'];
                    $traveler['invoice_type'] = $data['traveler']['invoice_type'][$k];
                    $traveler['invoice_code'] = $data['traveler']['invoice_code'][$k];
                    $traveler['invoice_num'] = $data['traveler']['invoice_num'][$k];
                    $traveler['invoice_money'] = $data['traveler']['invoice_money'][$k];
                    $traveler['total'] = $data['traveler']['total'][$k];
                    $traveler['remark'] = $data['traveler']['remark'][$k];
                    $travelers[] = $traveler;
                    // 计算总发票费用
                    $total = $data['traveler']['total'][$k] + $total;
                }
            }

            // 预支付处理
            $flag = Db::name('driver_prepayment')
                ->where('group_id', $data['dispatch_group_id'])
                ->find();

            $total = $total + $flag['reimbursement'];

            if ($flag) {
                // 获取该订单的预支付标准
                $prepaid_expenses = Db::name('dispatch_traveler_group')
                    ->where('id', $data['dispatch_group_id'])
                    ->value('prepaid_expenses');

                // 获取司机抵消金额
                $admin_user = Db::name('admin_user')
                    ->alias('au')
                    ->join('tp_dispatch_traveler_group dtg', 'dtg.driver_user_id=au.id', 'left')
                    ->where('dtg.id', $data['dispatch_group_id'])
                    ->field('au.*')
                    ->find();

                $driver_offset = $admin_user['offset'];

                // 计算抵消金额
                $offset = $total - $prepaid_expenses;
                Db::name('admin_user')
                    ->alias('au')
                    ->join('tp_dispatch_traveler_group dtg', 'dtg.driver_user_id=au.id', 'left')
                    ->where('dtg.id', $data['dispatch_group_id'])
                    ->field('au.*')
                    ->setField('au.offset', $offset);

                // 判断是否有计算过实际打款
                if ($flag['actual_money'] === 0 || $flag['actual_money'] === '' || $flag['actual_money'] === null) {
                    // 计算实际打款
                    $actual_money = $prepaid_expenses + $driver_offset;
                    // 清空司机抵消金额
                    Db::name('admin_user')
                        ->where('id', $admin_user['id'])
                        ->setField('offset', 0);
                } else {
                    $actual_money = $flag['actual_money'];
                }

                Db::name('driver_prepayment')
                    ->where('group_id', $data['dispatch_group_id'])
                    ->update([
                        'reimbursement' => $total,
                        'offset' => $offset,
                        'actual_money' => $actual_money,
                    ]);
            }

            // 添加发票记录
            $result = Db::name('driver_invoice')
                ->insertAll($travelers);

            if ($result) {
                return ajax_return_adv('添加成功');
            } else {
                return ajax_return_adv_error('添加失败');
            }

        } else {

            $dispatch = Db::name('dispatch_traveler_group')
                ->alias('dtg')
                ->join('tp_admin_user au', 'dtg.driver_user_id=au.id', 'left')
                ->join('tp_route r', 'dtg.route_id=r.id', 'left')
                ->where('dtg.status', 1)
                ->where('dtg.isdelete', 0)
                ->field('dtg.*,au.realname,r.title')
                ->select();
            $this->view->assign('dispatch_list', $dispatch);
            return $this->view->fetch();
        }
    }

    /**
     * 编辑
     * @return mixed
     */
    public function edit()
    {
        $data = input();

        if ($this->request->isAjax()) {

//            halt($data);
            $driver_invoice = Db::name('driver_invoice')
                ->where('id', $data['id'])
                ->find();


            // 预支付处理
            $flag = Db::name('driver_prepayment')
                ->where('group_id', $data['dispatch_group_id'])
                ->find();

            $total = $flag['reimbursement'] - $driver_invoice['total'] + $data['total'];

            if ($flag) {
                // 获取该订单的预支付标准
                $prepaid_expenses = Db::name('dispatch_traveler_group')
                    ->where('id', $data['dispatch_group_id'])
                    ->value('prepaid_expenses');

                // 获取司机抵消金额
                $admin_user = Db::name('admin_user')
                    ->alias('au')
                    ->join('tp_dispatch_traveler_group dtg', 'dtg.driver_user_id=au.id', 'left')
                    ->where('dtg.id', $data['dispatch_group_id'])
                    ->field('au.*')
                    ->find();

                $driver_offset = $admin_user['offset'];

                // 计算抵消金额
                $offset = $total - $prepaid_expenses;
                Db::name('admin_user')
                    ->alias('au')
                    ->join('tp_dispatch_traveler_group dtg', 'dtg.driver_user_id=au.id', 'left')
                    ->where('dtg.id', $data['dispatch_group_id'])
                    ->field('au.*')
                    ->setField('au.offset', $offset);

                // 判断是否有计算过实际打款
                if ($flag['actual_money'] === 0 || $flag['actual_money'] === '' || $flag['actual_money'] === null) {
                    // 计算实际打款
                    $actual_money = $prepaid_expenses + $driver_offset;
                    // 清空司机抵消金额
                    Db::name('admin_user')
                        ->where('id', $admin_user['id'])
                        ->setField('offset', 0);
                } else {
                    $actual_money = $flag['actual_money'];
                }

                Db::name('driver_prepayment')
                    ->where('group_id', $data['dispatch_group_id'])
                    ->update([
                        'reimbursement' => $total,
                        'offset' => $offset,
                        'actual_money' => $actual_money,
                    ]);
            }


            $result = Db::name('driver_invoice')
                ->where('id', $data['id'])
                ->strict(false)
                ->update($data);

            if ($result) {
                return ajax_return_adv('编辑成功');
            } else {
                return ajax_return_adv_error('编辑失败');
            }

        } else {

            $reslut = Db::name('driver_invoice')
                ->where('id', $data['id'])
                ->find();
            $dispatch = Db::name('dispatch_traveler_group')
                ->alias('dtg')
                ->join('tp_admin_user au', 'dtg.driver_user_id=au.id', 'left')
                ->join('tp_route r', 'dtg.route_id=r.id', 'left')
                ->where('dtg.status', 1)
                ->where('dtg.isdelete', 0)
                ->field('dtg.*,au.realname,r.title')
                ->select();
            $this->view->assign('dispatch_list', $dispatch);
            $this->view->assign('vo', $reslut);
            return $this->view->fetch();
        }
    }

    /**
     * 删除
     * @return mixed
     */
    public function delete()
    {
        $data = input();

        $data['id'] = explode(',', $data['id']);

        foreach ($data['id'] as $k=>$v){

            $driver_invoice = Db::name('driver_invoice')
                ->where('id', $v)
                ->find();

            // 预支付处理
            $flag = Db::name('driver_prepayment')
                ->where('group_id', $driver_invoice['dispatch_group_id'])
                ->find();

            $total = $flag['reimbursement'] - $driver_invoice['total'];

            if ($flag) {
                // 获取该订单的预支付标准
                $prepaid_expenses = Db::name('dispatch_traveler_group')
                    ->where('id', $driver_invoice['dispatch_group_id'])
                    ->value('prepaid_expenses');

                // 获取司机抵消金额
                $admin_user = Db::name('admin_user')
                    ->alias('au')
                    ->join('tp_dispatch_traveler_group dtg', 'dtg.driver_user_id=au.id', 'left')
                    ->where('dtg.id', $driver_invoice['dispatch_group_id'])
                    ->field('au.*')
                    ->find();

                $driver_offset = $admin_user['offset'];

                // 计算抵消金额
                $offset = $total - $prepaid_expenses;
                Db::name('admin_user')
                    ->alias('au')
                    ->join('tp_dispatch_traveler_group dtg', 'dtg.driver_user_id=au.id', 'left')
                    ->where('dtg.id', $driver_invoice['dispatch_group_id'])
                    ->field('au.*')
                    ->setField('au.offset', $offset);

                // 判断是否有计算过实际打款
                if ($flag['actual_money'] === 0 || $flag['actual_money'] === '' || $flag['actual_money'] === null) {
                    // 计算实际打款
                    $actual_money = $prepaid_expenses + $driver_offset;
                    // 清空司机抵消金额
                    Db::name('admin_user')
                        ->where('id', $admin_user['id'])
                        ->setField('offset', 0);
                } else {
                    $actual_money = $flag['actual_money'];
                }

                Db::name('driver_prepayment')
                    ->where('group_id', $driver_invoice['dispatch_group_id'])
                    ->update([
                        'reimbursement' => $total,
                        'offset' => $offset,
                        'actual_money' => $actual_money,
                    ]);
            }
        }

        $result = Db::name('driver_invoice')
            ->whereIn('id', $data['id'])
            ->setField('isdelete', 1);

        if ($result) {
            return ajax_return_adv('删除成功');
        } else {
            return ajax_return_adv_error('删除失败');
        }
    }

}